package com.fyy.netty.chapter01.c2;

import com.fyy.netty.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author fyy
 * @Description
 * @Date 2021/4/21 14:12
 */
@Slf4j
public class Server {

    public static void bioServer() throws IOException {
        //1.声明全局的ByteBuffer用于处理客户端数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //2.声明服务器通道，等待客户端接入
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false); //改为非阻塞模式
        //3.绑定端口
        ssc.bind(new InetSocketAddress("127.0.0.1",8080));
        //4.声明一个集合，保存连接的客户端
        List<SocketChannel> socketChannels = new ArrayList<>();
        while (true){
            //5.阻塞
            SocketChannel socketChannel = ssc.accept(); //非阻塞线程，等待客户端接入
            socketChannels.add(socketChannel); //保存新接入的客户端
            for (SocketChannel sc : socketChannels) {
                sc.read(buffer); //阻塞线程，等待客户端数据
                buffer.flip();
                ByteBufferUtil.debugRead(buffer);
                buffer.clear();
            }
        }
    }

    public static void nioServer() throws IOException {
        //1.声明全局的ByteBuffer用于处理客户端数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //2.声明服务器通道，等待客户端接入
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false); //改为非阻塞模式
        //3.绑定端口
        ssc.bind(new InetSocketAddress("127.0.0.1",8080));
        //4.声明一个集合，保存连接的客户端
        List<SocketChannel> socketChannels = new ArrayList<>();
        while (true){
            //5.阻塞
            SocketChannel socketChannel = ssc.accept(); //非阻塞线程，等待客户端接入
            if(socketChannel != null){
                socketChannels.add(socketChannel); //保存新接入的客户端
                socketChannel.configureBlocking(false); //改为非阻塞模式
            }
            for (SocketChannel sc : socketChannels) {
                int read = sc.read(buffer);//非阻塞，等待客户端数据
                if(read > 0){
                    log.info("客户端:{}",sc.getRemoteAddress());
                    buffer.flip();
                    log.info("客户端信息:{}",StandardCharsets.UTF_8.decode(buffer));
                    buffer.clear();
                }
            }
        }
    }

    public static void selectorServer() throws IOException {
        //声明Selector,管理多个Channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false); //设置为非阻塞模式
        //注册到selector,并获得监听的key
        SelectionKey sscKey = ssc.register(selector, 0, null);
        sscKey.interestOps(SelectionKey.OP_ACCEPT); //注册感兴趣的事件
        ssc.bind(new InetSocketAddress("127.0.0.1",8080));
        while (true){
            //关注事件
            int select = selector.select(); //无事件时阻塞
            //处理事件
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()){
                SelectionKey key = iter.next();
                //key.cancel(); //取消处理，避免死循环
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false); //设置为非阻塞模式
                    ByteBuffer buffer = ByteBuffer.allocate(10); //注册附件
                    SelectionKey scKey = sc.register(selector, 0, buffer); //注册到selector,并获得监听的key
                    scKey.interestOps(SelectionKey.OP_READ); //注册感兴趣的事件
                }
                if(key.isReadable()){
                    try {
                        SocketChannel channel = (SocketChannel)key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment(); //获取key关联的附件
                        int read = channel.read(buffer); //正常断开返回-1
                        if(read == -1){
                            key.cancel(); //取消这个key的所有监听事件
                        }else{
                            split(buffer);
                            if(buffer.position() == buffer.limit()){
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2); //扩容
                                //复制拷贝
                                buffer.flip();
                                newBuffer.put(buffer);
                                //替换附件
                                key.attach(newBuffer);
                            }
                        }
                    }catch (Exception e){
                        key.cancel(); //取消这个key的所有监听事件
                    }
                }
                iter.remove(); //处理完删除key，否则下次会处理到已处理的key
            }

        }
    }

    public static void split(ByteBuffer buffer){
        //切换未读
        buffer.flip();
        for (int i = 0; i < buffer.limit(); i++) {
            if(buffer.get(i) == '\n'){
                int length = i - buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                //读取
                for (int j = 0; j < length; j++) {
                    target.put(buffer.get());
                }
                buffer.get(); //读取分隔符，丢掉
                target.flip();
                System.out.println(StandardCharsets.UTF_8.decode(target));
                target.clear();
            }
        }
        //切换写
        buffer.compact(); //不能使用clear
    }

    public static void main(String[] args) throws IOException {
        selectorServer();
    }


}
